package com.dormitory.javadormitory.controller;

import com.dormitory.javadormitory.common.Result;
import com.dormitory.javadormitory.entity.ChangePasswordDTO;
import com.dormitory.javadormitory.entity.Token;
import com.dormitory.javadormitory.entity.UserAccount;
import com.dormitory.javadormitory.exception.CustomException;
import com.dormitory.javadormitory.service.UserAccountService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserAccountController {

    @Resource
    private UserAccountService userAccountService;

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserAccount userAccount,HttpServletRequest request){
        Token loginUser = userAccountService.login(userAccount);
        System.out.println("3："+request.getSession().getId());
        return Result.success(loginUser);
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody UserAccount userAccount,@RequestParam String captcha,HttpServletRequest request){
        System.out.println(captcha);
        if (captcha==null||"".equals(captcha)){
            throw new CustomException("请输入验证码");
        }
        if (!request.getSession().getAttribute("captcha").equals(captcha)){
            return Result.error(401,"验证码错误");
        }
        UserAccount regUAInfo = userAccountService.register(userAccount);
        return Result.success();
    }

    //修改密码
    @PostMapping("/change-password")
    public Result changePwd(@RequestBody ChangePasswordDTO changePasswordDTO, HttpServletRequest request){
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        System.out.println("前端传来的验证码：" + changePasswordDTO.getCaptcha());
        System.out.println("2:"+session.getId());
        if (changePasswordDTO.getCaptcha()==null||"".equals(changePasswordDTO.getCaptcha())){
            throw new CustomException("请输入验证码");
        }
        String captcha = (String) session.getAttribute("captcha");
        if (!changePasswordDTO.getCaptcha().equals(captcha)){
            return Result.error(401,"验证码错误");
        }
        userAccountService.changePwd(changePasswordDTO,userId);
        return Result.success();
    }

    //获取id
    @GetMapping("/all_user")
    public Result getAllUserAccount(HttpServletRequest request){
        HttpSession session = request.getSession();
        System.out.println("用户Id："+session.getAttribute("userId"));
        return Result.success(userAccountService.getUserAccounts());
    }


}
